<template>
  <div>
    <div class="page-header">
      <h2>人员管理</h2>
      <div>
        <input type="file" accept=".xlsx" @change="importUsers" style="display:none" ref="fileInput"/>
        <button class="btn" @click="openAdd">新增人员</button>
        <button class="btn" @click="showImportDialog = true">导入</button>
        <button class="btn" @click="exportUsers">导出</button>
        <input v-model="search" placeholder="搜索人员" class="search-input" />
      </div>
    </div>
    <table class="data-table">
      <thead>
        <tr>
          <th>用户名</th>
          <th>真实姓名</th>
          <th>邮箱</th>
          <th>手机号</th>
          <th>职务</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in filteredList" :key="item.id">
          <td>{{ item.name }}</td>
          <td>{{ item.truename }}</td>
          <td>{{ item.email }}</td>
          <td>{{ item.phone }}</td>
          <td>{{ item.role }}</td>
          <td class="action-cell">
            <button class="btn" @click="edit(item)">编辑</button>
            <button class="btn" @click="remove(item.id)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
    <div v-if="showAdd" class="modal">
      <div class="modal-content">
        <h3>{{ editId ? '编辑人员' : '新增人员' }}</h3>
        <input v-model="form.name" placeholder="用户名" class="input-box" />
        <input v-model="form.truename" placeholder="真实姓名" class="input-box" />
        <input v-model="form.email" placeholder="邮箱" class="input-box" />
        <input v-model="form.phone" placeholder="手机号" class="input-box"/>
        <select v-model="form.role" class="input-box select-box">
          <option value="" disabled>请选择职务</option>
          <option value="经理">经理</option>
          <option value="分部长">分部长</option>
          <option value="普通员工">普通员工</option>
        </select>
        <div class="modal-actions">
          <button class="btn" @click="save">保存</button>
          <button class="btn" @click="close">取消</button>
        </div>
      </div>
    </div>
    <div v-if="showImportDialog" class="modal">
      <div class="modal-content">
        <h3>请选择导入方式</h3>
        <div style="margin: 20px 0;">
          <button class="btn" @click="handleDirectImport">直接导入</button>
          <button class="btn" @click="downloadTemplate">下载模板再导入（推荐）</button>
        </div>
        <button class="btn" @click="showImportDialog = false">取消</button>
      </div>
    </div>  
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import * as XLSX from 'xlsx'
const list = ref([])
const search = ref('')
const showAdd = ref(false)
const editId = ref(null)
const form = ref({ name: '', truename: '', email: '', phone: '', role: '' })
const fileInput = ref(null)
const showImportDialog = ref(false)

async function fetchList() {
  const res = await axios.get('http://localhost:8080/api/users')
  if (res.data.length === 0) {
    await axios.post('http://localhost:8080/api/users', {
      username: 'admin',
      truename: '崔小彤',
      email: 'admin@example.com',
      phone: '13800000000',
      role: '经理'
    });
    const newRes = await axios.get('http://localhost:8080/api/users')
    list.value = newRes.data.map(item => ({
      name: item.username,
      truename: item.truename,
      email: item.email,
      phone: item.phone,
      role: item.role,
      id: item.id
    }))
  } else {
    list.value = res.data.map(item => ({
      name: item.username,
      truename: item.truename,
      email: item.email,
      phone: item.phone,
      role: item.role,
      id: item.id
    }))
  }
}

onMounted(fetchList)

const filteredList = computed(() =>
  list.value.filter(item =>
    item.name.includes(search.value) ||
    item.truename.includes(search.value)||
    item.email.includes(search.value) ||
    item.phone.includes(search.value) ||
    item.role.includes(search.value)
  )
)

function openAdd() {
  editId.value = null
  form.value = { name: '', truename: '', email: '', phone: '', role: '' }
  showAdd.value = true
}
function edit(item) {
  editId.value = item.id
  form.value = { name: item.name, truename: item.truename, email: item.email, phone: item.phone, role: item.role }
  showAdd.value = true
}
async function remove(id) {
  await axios.delete(`http://localhost:8080/api/users/${id}`)
  await fetchList()
}
async function save() {
  if (form.value.phone && form.value.phone.length !== 11) {
    alert('电话号码位数错误，必须是11位！')
    return
  }
  const payload = {
    username: form.value.name,
    truename: form.value.truename,
    email: form.value.email,
    phone: form.value.phone,
    role: form.value.role
  }
  if (editId.value) {
    await axios.put(`http://localhost:8080/api/users/${editId.value}`, payload)
  } else {
    await axios.post('http://localhost:8080/api/users', payload)
  }
  await fetchList()
  close()
}
function close() {
  showAdd.value = false
  editId.value = null
  form.value = { name: '', truename: '', email: '', phone: '', role: '' }
}
function handleDirectImport() {
  showImportDialog.value = false;
  fileInput.value.click();
}
function downloadTemplate() {
  const header = ['用户名','真实姓名','邮箱','手机号','职务'];
  const ws = XLSX.utils.aoa_to_sheet([header]);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '人员模板');
  XLSX.writeFile(wb, '人员导入模板.xlsx');
}
// 导出为Excel
function exportUsers() {
  const header = ['用户名','真实姓名','邮箱','手机号','职务'];
  const data = list.value.map(u => [u.name, u.truename, u.email, u.phone, u.role]);
  const ws = XLSX.utils.aoa_to_sheet([header, ...data]);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '人员数据');
  XLSX.writeFile(wb, '人员数据.xlsx');
}
// 导入Excel
async function importUsers(e) {
  const file = e.target.files[0];
  if (!file) return;
  const reader = new FileReader();
  reader.onload = async function(evt) {
    const data = new Uint8Array(evt.target.result);
    const workbook = XLSX.read(data, { type: 'array' });
    const sheet = workbook.Sheets[workbook.SheetNames[0]];
    const rows = XLSX.utils.sheet_to_json(sheet, { header: 1 });
    const expectedHeader = ['用户名','真实姓名','邮箱','手机号','职务'];
    const fileHeader = rows[0] || [];
    const isHeaderValid = expectedHeader.every((h, i) => h === fileHeader[i]);
    if (!isHeaderValid) {
      alert('导入失败：表头格式不正确，请使用模板或检查列顺序！');
      return;
    }
    const users = rows.slice(1).map((row, idx) => {
      if (row.length < 5 || row.some(cell => cell === undefined || cell === null)) {
        alert(`第${idx + 2}行数据不完整，已跳过`);
        return null;
      }
      const phone = String(row[3] || '');
      if (phone && phone.length !== 11) {
        alert(`第${idx + 2}行电话号码位数错误，必须是11位！`);
        return null;
      }
      return {
        username: row[0] || '',
        truename: row[1] || '',
        email: row[2] || '',
        phone: row[3] || '',
        phone: phone,
        role: row[4] || ''
      };
    }).filter(Boolean);
    for (const u of users) {
      await axios.post('http://localhost:8080/api/users', u);
    }
    await fetchList();
  };
  reader.readAsArrayBuffer(file);
}

</script>

<style scoped>
@import '../assets/style.css';
.page-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; }
.data-table { width: 100%; border-collapse: collapse; background: #fff; }
.data-table th, .data-table td { border: 1px solid #eee; padding: 8px; }
.btn { background: #16a085; color: #fff; border: none; padding: 6px 16px; border-radius: 4px; cursor: pointer; margin-right: 8px; }
.search-input { padding: 6px 12px; border: 1px solid #ccc; border-radius: 4px;margin-top: 8px;  }
.modal { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.2); display: flex; align-items: center; justify-content: center; }
.modal-content { background: #fff; padding: 24px; border-radius: 8px; min-width: 300px; }
.modal-actions { margin-top: 16px; display: flex; gap: 12px; }
.action-cell { text-align: center; }

.input-box {
  width: 100%;
  padding: 18px 16px;
  border: 3px solid #ecf0f1;
  border-radius: 24px;
  background: #fafafa;
  font-size: 20px;
  color: #222;
  margin-bottom: 8px;
  box-sizing: border-box;
  outline: none;
  transition: border 0.2s;
}
.input-box:focus {
  border-color: #16a085;
}
.input-box::placeholder {
  color: #bbb;
}


.select-box {
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  background: #fafafa;
  border: 3px solid #ecf0f1;
  border-radius: 24px;
  font-size: 20px;
  color: #222;
  padding: 18px 16px;
  width: 100%;
  box-sizing: border-box;
  outline: none;
  margin-bottom: 8px;
  transition: border 0.2s;
  background-image: url('data:image/svg+xml;utf8,<svg fill="%23bbb" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"/></svg>');
  background-repeat: no-repeat;
  background-position: right 16px center;
  background-size: 24px 24px;
}
</style> 